<template>
  <div class="app-container calendar-list-container"
       v-wechat-title="'OSS图片管理'">
    <el-card class="box-card" style="margin-top: 10px">
      <div slot="header" class="clearfix">
        <el-row>
          <el-cascader
              ref="catalog"
              v-model="cascaderValue"
              placeholder="图片目录"
              :options="catalogList"
              :props="{ checkStrictly: true }"
              clearable>
          </el-cascader>
          <el-button style="margin-left: 10px"
                     type="info"
                     icon="el-icon-search"
                     @click="handleQuery">查询
          </el-button>
          <el-button class="filter-item"
                     type="primary"
                     icon="el-icon-edit"
                     :disabled="isAuth('sys:oss:upload')"
                     @click="handleUpload">上传图片
          </el-button>
          <!--          <el-button class="filter-item"-->
          <!--                     type="warning"-->
          <!--                     icon="el-icon-document-copy"-->
          <!--                     :disabled="isAuth('sys:oss:upload')"-->
          <!--                     @click="handleAddBatch">批量添加图片到本地-->
          <!--          </el-button>-->
          <!--                        <el-button class="filter-item" type="primary" icon="el-icon-refresh">{{chooseTitle}}</el-button>-->
          <el-button class="filter-item"
                     type="danger"
                     icon="el-icon-delete"
                     :disabled="this.pictureValue.length < 0 || isAuth('sys:oss:delete')"
                     @click="handleDeleteBatch">删除选中
          </el-button>
        </el-row>

      </div>
      <el-row>
        <el-col style="padding: 6px;"
                :xs="24" :sm="12" :md="8" :lg="4" :xl="4"
                v-for="item in pictureList" :key="item.url">
          <el-card style="height: 300px" :body-style="{ padding: '0px', textAlign: 'center' }" shadow="always">
            <input style="position: absolute;z-index: 100;" type="checkbox" :id="item.url" @click="checked(item)">
            <el-image :src="item.url"
                      style="cursor:pointer;width: 254px; height: 200px"
                      fit="scale-down"
                      :preview-src-list="[item.url]"/>
            <div style="padding: 18px;">
              <span class="media-title">{{ item.picName.substr(0, item.picName.indexOf(".")) }}</span>
              <div class="bottom clearfix" style="margin-top: 10px">
                <el-button-group>
                  <el-tooltip class="item" effect="dark" content="复制图片地址" placement="bottom-start"
                              style="margin-right: 2px">
                    <el-button type="primary"
                               size="mini"
                               icon="el-icon-copy-document"
                               :disabled="!isAuth('picture:oss:copyLink')"
                               @click="copyUrl(item.url)"/>
                  </el-tooltip>

                  <el-tooltip class="item" effect="dark" content="删除图片" placement="bottom-start"
                              style="margin-right: 2px">
                    <el-button type="danger"
                               size="mini"
                               icon="el-icon-delete"
                               :disabled="!isAuth('picture:oss:delete')"
                               @click="handleDelete(item)"/>
                  </el-tooltip>
                </el-button-group>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <pagination
          v-show="pagination.total>0"
          :limit.sync="pagination.pageSize"
          :page.sync="pagination.currentPage"
          :total="pagination.total"
          :page-sizes="[6, 12, 18, 24]"
          @pagination="handleQuery"
      />
    </el-card>

    <pic-upload v-if="uploadVisible" :catalogList="catalogList" ref="picUpload" @handleQuery="reloadData"></pic-upload>

  </div>
</template>

<script>

import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
import {getOssPicture, getOssCatalog, deleteOssPicture} from '@/api/ossPicture'
import picUpload from "@/views/picture/pic-upload";

export default {
  name: "pictureSort",
  components: {ImageCropper, PanThumb, picUpload},
  data() {
    return {
      // 非多个禁用
      uploadVisible: false,
      multiple: true,
      pictureList: [],
      catalogList: [],
      cascaderValue: [],
      addDialog: false,
      addDialogForm: {
        type: '0',
        name: '',
      },
      imageCropperShow: false,
      imageCropperKey: 0,
      radioTypeList: [],
      pictureValue: [], //选中图片value集合
      pagination: {
        currentPage: 1,
        pageSize: 6,
        total: 0
      },
      queryParams: {
        catalog: '',
        currentPage: 1,
        pageSize: 10
      },
    }
  },
  methods: {
    handleQuery() {
      this.queryParams.currentPage = this.pagination.currentPage
      this.queryParams.pageSize = this.pagination.pageSize
      if (this.cascaderValue && this.cascaderValue.length > 0) {
        this.queryParams.catalog = this.cascaderValue.join('/');
      } else {
        this.queryParams.catalog = ''
      }
      getOssPicture(this.queryParams).then(res => {
        if (res.status) {
          let picture = res.data
          this.pagination.pageSize = picture.pageSize
          this.pagination.currentPage = picture.currentPage
          this.pagination.total = picture.total
          if (picture.pageList) {
            let arr = this.divisionList(picture.pageList);
            this.pictureList = arr
          } else {
            this.pictureList = picture.pageList
          }
        } else {
          this.$message.error('获取OSS图片信息失败')
        }
      });
    },
    divisionList(data) {
      let list = []
      data.forEach(item => {
        let obj = {
          url: '',
          picName: ''
        }
        let index = item.lastIndexOf('/')               //获取最后一次出现‘/’的下标
        obj.picName = item.substring(index + 1, item.length)        //获取图片名称
        obj.url = item
        list.push(obj)
      })
      return list
    },
    //打开添加模态框，添加照片
    handleUpload() {
      this.uploadVisible = true
      this.$nextTick(() => {
        this.$refs.picUpload.init()
      })
    },
    //点击单选
    checked(data) {
      let value = data.url
      let idIndex = this.pictureValue.indexOf(value);
      if (idIndex >= 0) {  //选过了
        this.pictureValue.splice(idIndex, 1);
      } else {
        this.pictureValue.push(value);
      }
    },
    //删除选中
    handleDeleteBatch() {
      if (this.pictureValue.length > 0) {
        this.$confirm(`是否删除选中的照片?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = this.splitPictureValue()
          deleteOssPicture(data.join()).then(res => {
            if (res.data.length > 0) {
              this.pictureValue = []
              this.$message.success('删除选中图片成功...')
              this.reloadData()
            } else {
              this.$message.error('删除选中图片失败...')
            }
          })
        }).catch(() => {
        });
      } else {
        this.$message.error('请先选中图片！')
        return
      }
    },
    //根据url分割成删除或添加所需要的信息
    splitPictureValue(data) {
      let dataList = this.pictureValue
      let temp = []
      dataList.forEach(item => {
        temp.push(item.substring(48))
      })
      return temp
    },
    //复制url到剪贴板
    copyUrl(url) {
      const oInput = document.createElement('input')
      oInput.value = url
      document.body.appendChild(oInput)
      oInput.select() // 选择对象
      document.execCommand('Copy') // 执行浏览器复制命令
      oInput.className = 'oInput'
      oInput.style.display = 'none'
      this.$message.success('复制链接到剪切板成功')
    },
    //删除图片
    handleDelete(data) {
      this.$confirm(`是否删除名字为${data.picName}的照片?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let temp = []
        temp.push(data.url.substring(48))
        deleteOssPicture(temp.join()).then(res => {
          if (res.data.length > 0) {
            this.$message.success('删除选中图片成功...')
            this.reloadData()
          } else {
            this.$message.error('删除选中图片失败...')
          }
        })
      }).catch(() => {
      });
    },
    //查询目录
    queryCatalog() {
      getOssCatalog().then(res => {
        this.catalogList = res.data
      })
    },
    //重载数据
    reloadData() {
      this.handleQuery()
      this.queryCatalog()
      this.cascaderValue = []
    }
  },
  created() {
    this.handleQuery()
    this.queryCatalog()
  }
}
</script>

<style scoped>

</style>
